

import {AppSendEventCallback} from "./i_app_send_event";
import IAppSendEvent from "./i_app_send_event";
import rpc from "@ohos.rpc";

export default class AppSendEventProxy implements IAppSendEvent {
    constructor(proxy) {
        this.proxy = proxy;
    }

    appSendEvent(data: Map<string, string>, callback: AppSendEventCallback): void
    {
        let option = new rpc.MessageOption();
        let dataSequence = rpc.MessageSequence.create();
        let replySequence = rpc.MessageSequence.create();
        dataSequence.writeInterfaceToken(this.proxy.getDescriptor());
        dataSequence.writeInt(data.size);
        for (let [key, value] of data) {
            dataSequence.writeString(key);
            dataSequence.writeString(value);
        }
        this.proxy.sendMessageRequest(AppSendEventProxy.COMMAND_APP_SEND_EVENT, dataSequence, replySequence, option).then((result: rpc.RequestResult) => {
            if (result.errCode === 0) {
                let errCodeVar = result.reply.readInt();
                let jsonVar = result.reply.readString();
                callback(errCodeVar,jsonVar);
            } else {
                let errCodeVar = result.reply.readInt();
                let jsonVar = result.reply.readString();
                callback(errCodeVar,jsonVar);
                console.log("sendMessageRequest failed, errCode: " + result.errCode);
            }
        }).catch((e: Error) => {
            console.log('sendMessageRequest failed, message: ' + e.message);
        }).finally(() => {
            dataSequence.reclaim();
            replySequence.reclaim();
        });
    }

    static readonly COMMAND_APP_SEND_EVENT = 1;
    private proxy
}

